/**
 * Created with IntelliJ IDEA
 * Description：模拟实现阻塞队列
 * User：chenshu
 * Date：2023-11-08
 * Time：21:59
 */
class MyBlockingQueue {
    private int[] queue = new int[1000];
    private int head;
    private int tail;
    volatile private int size;

    public void put(Integer val) throws InterruptedException {
        synchronized (this) {
            while (size == queue.length) {
                this.wait();
            }
            queue[tail] = val;
            tail++;
            if (tail == 1000) {
                tail = 0;
            }
            size++;
            this.notifyAll();
        }
    }
    public Integer take() throws InterruptedException {
        int ret = 0;
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }
            ret = queue[head];
            head++;
            if (head == 1000) {
                head = 0;
            }
            size--;
            this.notifyAll();
        }
        return ret;
    }
}
public class Demo5 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread Customer = new Thread(() -> {
            while (true) {
                try {
                    int n = queue.take();
                    Thread.sleep(500);
                    System.out.println("消费者取数据：" + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread Producer = new Thread(() -> {
            int n = 1;
            while(true) {
                try {
                    System.out.println("生产者存数据：" + n);
                    queue.put(n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Customer.start();
        Producer.start();
    }
}
